#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
set_github_prefix.py
为 GitHub HTTPS 克隆地址统一添加或移除“加速前缀”，自动补齐末尾“/”。
修复点：在 git config 的 url 子段名上**强制加引号**，避免生成无效键。
"""

import argparse
import subprocess
import sys
import re

GITHUB_BASE = "https://github.com/"

def run_git(args):
    p = subprocess.run(["git"] + args, capture_output=True, text=True, check=False)
    return p.returncode, (p.stdout or "") + (p.stderr or "")

def normalize_prefix(prefix: str) -> str:
    s = prefix.strip()
    if not (s.startswith("http://") or s.startswith("https://")):
        raise ValueError("前缀必须以 http:// 或 https:// 开头")
    return s.rstrip("/") + "/"

def show_rules() -> str:
    rc, out = run_git(["config", "--global", "--get-regexp", r"^url\..*\.insteadof$"])
    if rc != 0:
        return "(无 url.*.insteadof 规则或读取失败)"
    lines = []
    for line in out.strip().splitlines():
        key, val = line.strip().split(None, 1)
        if val.strip() == GITHUB_BASE:
            lines.append(line)
    return "\n".join(lines) if lines else "(无与 https://github.com/ 相关的重写规则)"

def set_prefix(prefix: str) -> str:
    pref = normalize_prefix(prefix)
    target = f'{pref}{GITHUB_BASE}'  # e.g. https://ghfast.top/https://github.com/
    # 关键修复：对子段名加引号
    rc, out = run_git(["config", "--global", f'url."{target}".insteadof', GITHUB_BASE])
    if rc != 0:
        raise RuntimeError(out.strip() or "git config 失败")
    return target

def unset_github_rules() -> str:
    """
    移除所有把 https://github.com/ 作为 insteadof 值的 url 子段。
    - 先找出子段名，再用 --remove-section 精准删除，避免奇怪键名残留。
    """
    rc, out = run_git(["config", "--global", "--get-regexp", r"^url\..*\.insteadof$"])
    if rc != 0:
        return "（无可移除项）"
    removed = []
    for line in out.strip().splitlines():
        key, val = line.strip().split(None, 1)
        if val.strip() != GITHUB_BASE:
            continue
        # key 形如：url."https://ghfast.top/https://github.com/".insteadof  或  url.https://https://ghfast.top/...（历史错误）
        m = re.match(r'^url\.(?P<sub>.+)\.insteadof$', key)
        if not m:
            continue
        sub = m.group("sub")
        # 尝试用带引号的形式删除整个子段（更干净）
        # 两次尝试：带引号与不带引号（兼容历史错误）
        rc1, _ = run_git(["config", "--global", "--remove-section", f'url.{sub}'])
        if rc1 != 0 and not (sub.startswith('"') and sub.endswith('"')):
            rc2, _ = run_git(["config", "--global", "--remove-section", f'url."{sub}"'])
        removed.append(sub)
    return "、".join(removed) if removed else "（无可移除项）"

def main():
    ap = argparse.ArgumentParser(description="为 GitHub HTTPS 克隆地址添加/移除加速前缀（自动补末尾“/”）")
    ap.add_argument("--prefix", type=str, default="",
                    help="要设置的前缀（例如：https://ghfast.top 或 https://ghfast.top/）。留空表示移除已有规则。")
    ap.add_argument("--show", action="store_true", help="仅显示当前与 GitHub 相关的重写规则。")
    args = ap.parse_args()

    if args.show:
        print("== 当前与 GitHub 相关的 url.*.insteadof 规则 ==")
        print(show_rules()); sys.exit(0)

    print("== 变更前规则 ==")
    print(show_rules())

    if args.prefix.strip():
        try:
            target = set_prefix(args.prefix)
            print(f"\n已设置前缀：{target}")
            print("效果示例：git clone https://github.com/owner/repo.git  将被重写为：")
            print(f"          {target}owner/repo.git")
        except Exception as e:
            print(f"\n设置失败：{e}", file=sys.stderr); sys.exit(1)
    else:
        removed = unset_github_rules()
        print(f"\n已移除规则：{removed}")

    print("\n== 变更后规则 ==")
    print(show_rules())

if __name__ == "__main__":
    main()
